<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="活动资讯标题" prop="eventTitle">
        <el-input
          v-model="queryParams.eventTitle"
          placeholder="请输入活动资讯标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="咨询电话" prop="eventPhone">
        <el-input
          v-model="queryParams.eventPhone"
          placeholder="请输入咨询电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:event:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:event:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:event:remove']"
        >删除
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:event:export']"
        >导出
        </el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="eventList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="活动资讯标题" align="center" prop="eventTitle"/>
      <el-table-column label="活动资讯封面图" align="center" prop="eventImg" style="width: 400px; height: 200px">
        <template v-slot:default="scope">
          <el-image :src="scope.row.eventImg" :zoom-rate="2.4" :max-scale="8" :min-scale="0.9"
                    :preview-src-list="[scope.row.eventImg]" fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="咨询电话" align="center" prop="eventPhone"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:event:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:event:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body class="modal-wrap">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="活动资讯标题" prop="eventTitle">
          <el-input v-model="form.eventTitle" placeholder="请输入活动资讯标题"  />
        </el-form-item>
        <el-form-item label="活动资讯封面图" prop="eventImg">
          <el-upload
            class="avatar-uploader"
            action
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleUploadForm"
            :accept="'.jpg,.png,.jpeg'"
          >
            <img v-if="imageUrl" :src="imageUrl" class="banner-img">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="咨询电话" prop="eventPhone">
          <el-input v-model="form.eventPhone" placeholder="请输入咨询电话"/>
        </el-form-item>
        <el-form-item label="资讯介绍" prop="eventDescribe">
          <WangEditor
            @changeData="handleEditorChange" 
            :content="editorContent"
          />
          <div class="editBox">
            <div></div>
            <span>最高2000字</span>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addEvent, delEvent, getEvent, listEvent, updateEvent } from '@/api/business/event'
import { uploadImage } from '@/api/business/banner';
import WangEditor from '@/components/WangEditor';

export default {
  name: 'Event',
  components: { WangEditor },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动管理表格数据
      eventList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventType: 2,
        eventTitle: null,
        eventImg: null,
        eventPhone: null,
        enrollEndTime: null,
        eventDescribe: null,
        state: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        eventTitle: [
          { required: true, message: '活动资讯标题不能为空', trigger: 'blur' }
        ],
        eventImg: [
          { required: true, message: '活动资讯封面图不能为空', trigger: 'blur' }
        ],
        eventPhone: [
          { required: true, message: '咨询电话不能为空', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message:'请输入正确的号码格式', trigger:'change' }
        ],
        eventDescribe: [
          { required: true, message: '资讯介绍不能为空', trigger: 'blur' }
        ]
      },
      imageUrl: '',
      editorContent: '',
      editorTextLen: 0,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleEditorChange (html, text) {
      this.form.eventDescribe = html;
      this.editorTextLen = text.length;
      if (this.editorTextLen > 2000) {
        this.$message.error("资讯介绍最多2000字");
      }
    },
    /** 查询活动管理列表 */
    getList() {
      this.loading = true
      listEvent(this.queryParams).then(response => {
        this.eventList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        eventType: 2,
        eventTitle: null,
        eventImg: null,
        eventPhone: null,
        enrollEndTime: null,
        eventDescribe: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.imageUrl = ''
      this.editorContent = ''
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加活动资讯'
      this.imageUrl = ''
      this.editorContent = ''
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getEvent(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改活动资讯'
        this.imageUrl = response.data.eventImg
        this.editorContent = response.data.eventDescribe
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.editorTextLen > 2000) {
            this.$message.error("赛事介绍最多2000字");
            return;
          }
          if (this.form.id != null) {
            updateEvent(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addEvent(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除活动资讯？').then(function() {
        return delEvent(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/event/export', {
        ...this.queryParams
      }, `event_${new Date().getTime()}.xlsx`)
    },
    // 上传图片
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!');
      }
      return isLt2M;
    },
    // 上传图片
    async handleUploadForm(param) {
      const formData = new FormData();
      let loading = this.$loading({
        lock: true,
        text: '上传中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      formData.append('file', param.file);
      try {
        const res = await uploadImage(formData, Math.floor(Math.random() * 10));
        this.imageUrl = res.data.url;
        this.form.eventImg = res.data.url;
        loading.close();
      } catch (e) {
        loading.close();
      }
    },
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader {
  ::v-deep .el-upload {
    width: 100px;
    height: 100px;
    border: 1px dotted #eee;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .avatar-uploader-icon {
    font-size: 24px;
  }
}
.banner-img {
  width: 100px;
  height: 100px;
  // margin-left: 20px;
}
.modal-wrap {
  ::v-deep .el-dialog__body {
    height: 600px;
    overflow-y: scroll;
  }
}
.editBox{
  display: flex;
  justify-content: space-between;
}
</style>